package cn.qicaiwang.open.websocket.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;

import cn.qicaiwang.open.common.entity.LoginUser;
import cn.qicaiwang.open.common.entity.Message;
import cn.qicaiwang.open.common.enums.MessageEventEnum;
import cn.qicaiwang.open.websocket.common.Constant;
import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpTemplateMsgServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

public class MessageUtil {
    /**
     * 向指定用户发送消息
     * @param webSocketSession
     * @param message
     */
    public static void sendMessage(WebSocketSession webSocketSession, Message message) {
        try {
            String msg = JSON.toJSONString(message);
            webSocketSession.sendMessage(new TextMessage(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向全部用户发送消息
     * @param message
     */
    public static void sendAllMessage(Message message) {
        Enumeration<String> keys = Constant.pool.keys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement();
            WebSocketSession session = Constant.pool.get(key);
            LoginUser loginUser = (LoginUser) session.getAttributes().get(Constant.WS_CONTEXT_HOLDER);

            message.setToUserId(loginUser.getId());
            sendMessage(session, message);
        }
    }

    /**
     * 向用户发送微信消息
     * @param service
     * @param openId
     * @param message
     * @throws WxErrorException
     */
    public static void sendWechatMessage(WxMpService service, String openId, Message message) throws WxErrorException {
        WxMpTemplateMsgServiceImpl wxMpTemplateMsgService = new WxMpTemplateMsgServiceImpl(service);
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setToUser(openId);

        if(MessageEventEnum.login.name().equals(message.getEvent())){ // 登录成功通知
            wxMpTemplateMessage.setTemplateId("zfixsU1BL-9iaQoEW1eweARhNBkrzRJMXahQwxYv_58");//模版ID
            List<WxMpTemplateData> datas = new ArrayList<WxMpTemplateData>();
            WxMpTemplateData thing4 = new WxMpTemplateData("thing4", message.getTitle());
            datas.add(thing4);
            WxMpTemplateData thing6 = new WxMpTemplateData("thing6", message.getResult());
            datas.add(thing6);
            WxMpTemplateData time3 = new WxMpTemplateData("time3", DateUtil.format(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
            datas.add(time3);
            wxMpTemplateMessage.setData(datas);
        }else if(MessageEventEnum.notice.name().equals(message.getEvent())){
            wxMpTemplateMessage.setTemplateId("SeEPGIXFk1SKxN27IyjxLEYTmJCbmhqroCNS4tueTrc");//模版ID
            List<WxMpTemplateData> datas = new ArrayList<WxMpTemplateData>();
            WxMpTemplateData first = new WxMpTemplateData("first", message.getTitle());
            datas.add(first);
            WxMpTemplateData keyword1 = new WxMpTemplateData("keyword1", message.getTitle().length() > 20 ? message.getTitle().substring(0, 20) : message.getTitle());
            datas.add(keyword1);
            WxMpTemplateData keyword2 = new WxMpTemplateData("keyword2", message.getMessage().getContent().length() > 20 ? message.getMessage().getContent().substring(0, 20) : message.getMessage().getContent());
            datas.add(keyword2);
            WxMpTemplateData keyword3 = new WxMpTemplateData("keyword3", StrUtil.isBlank(message.getResult()) ? "已完成" : message.getResult());
            datas.add(keyword3);
            WxMpTemplateData remark = new WxMpTemplateData("remark", message.getMessage().getContent());
            datas.add(remark);
            wxMpTemplateMessage.setData(datas);
        }else if(MessageEventEnum.message.name().equals(message.getEvent())){
            wxMpTemplateMessage.setTemplateId("bmNp4DbnTt2VHQi35XrYWly1c76-SPoDtkmXc8NPVLI");//模版ID
            List<WxMpTemplateData> datas = new ArrayList<WxMpTemplateData>();
            WxMpTemplateData first = new WxMpTemplateData("first", message.getTitle());
            datas.add(first);
            WxMpTemplateData keyword1 = new WxMpTemplateData("keyword1", message.getMessage().getContent().length() > 20 ? message.getMessage().getContent().substring(0, 20) : message.getMessage().getContent());
            datas.add(keyword1);
            WxMpTemplateData keyword2 = new WxMpTemplateData("keyword2", DateUtil.format(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
            datas.add(keyword2);
            WxMpTemplateData keyword3 = new WxMpTemplateData("keyword3", "待回复");
            datas.add(keyword3);
            WxMpTemplateData remark = new WxMpTemplateData("remark", "请登录小鹿线客户关系管理系统查看聊天记录");
            datas.add(remark);
            wxMpTemplateMessage.setData(datas);
        }
        wxMpTemplateMsgService.sendTemplateMsg(wxMpTemplateMessage);
    }


    public static void sendEmailMessage(MailAccount mailTemplate, String email, Message message){
        String html = "<h2>小鹿线CRM系统自动发送</h2>";
        html += "<p>" + message.getMessage().getContent() + "</p>";
        MailUtil.send(mailTemplate, email, "小鹿线CRM系统自动发送-（小鹿线），勿回复。", html,true);
    }
}
